package com.peng.leetcode.slidingWindow;

import java.util.HashMap;
import java.util.Map;

/**
 * TotalFruit
 * 904. 水果成篮
 * https://leetcode.cn/problems/fruit-into-baskets/
 * <p>
 * Created on 2022/12/5
 *
 * @author lupeng
 */
public class TotalFruit {

    public static void main(String[] args) {
        //[0,1,2,2]
        System.out.println(new TotalFruit().totalFruit(new int[]{0, 1, 2, 2}));
    }

    public int totalFruit(int[] fruits) {
        int ans = 0;
        int left = 0, right = 0;
        Map<Integer, Integer> m = new HashMap<>();
        while (right < fruits.length) {
            int fruit = fruits[right];
            m.put(fruit, m.getOrDefault(fruit, 0) + 1);
            while (m.size() > 2) {
                m.put(fruits[left], m.get(fruits[left]) - 1);
                if (m.get(fruits[left]) == 0) {
                    m.remove(fruits[left]);
                }
                left++;
            }
            ans = Math.max(ans, right - left + 1);
            right++;
        }
        return ans;
    }
}
